<template>
  <div class="form-container">
    <div class="scrollable-content">
      <form @submit.prevent="handleSubmit" class="ai-form">
        <!-- 参考图 - 使用ImageUploader组件 -->
        <div class="form-group">
          <label for="prompt" class="form-label">Upload Image</label>
          <ImageUploader v-model="formData.url" class="image-uploader" />
        </div>
        <!-- Prompt 多行文本输入框 -->
        <div class="form-group">
          <label for="prompt" class="form-label">Description</label>
          <div class="textarea-container">
            <textarea
              id="prompt"
              v-model="formData.prompt"
              class="form-textarea"
              :maxlength="maxPromptLength"
              placeholder="Describe the area you want to modify..."
              resize="none"></textarea>
            <div class="prompt-bar">
              <div class="char-counter">{{ formData.prompt.length }}/{{ maxPromptLength }}</div>
            </div>
          </div>
        </div>
      </form>
    </div>
    <!-- 提交按钮 - 固定在底部 -->
    <div class="button-container">
      <button
        type="submit"
        class="submit-button"
        :disabled="!isFormValid || isSubmitting"
        @click="handleSubmit">
        Generate Now
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { AiAPI } from '@/api/ai';
  import ImageUploader from '@/components/ImageUploader.vue';
  import { AIType } from '@/types/ai';
  import { ref, computed, onMounted, watch } from 'vue';
  import { useAiStore } from '@/store/ai';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';

  const aiStore = useAiStore();
  const route = useRoute();
  const router = useRouter();

  // 表单数据模型
  const formData = ref({
    type: AIType.EDIT,
    template_id: 0,
    prompt: '',
    url: '', // 用于存储上传后的图片URL
  });

  // 最大提示文本长度
  const maxPromptLength = 1000;
  // 提交状态
  const isSubmitting = ref(false);
  // 表单验证
  const isFormValid = computed(() => {
    return formData.value.url && formData.value.prompt.length > 0;
  });

  // 处理路由中的img参数
  const handleImgParam = () => {
    const imgParam = route.query.img as string;
    if (imgParam) {
      formData.value.url = decodeURIComponent(imgParam);

      // 清除URL中的img参数
      const query = { ...route.query };
      delete query.img;
      router.replace({
        path: route.path,
        query: query,
      });
    }
  };

  // 组件初始化时加载分类数据和路由参数
  onMounted(() => {
    handleImgParam(); // 调用处理img参数的函数
  });

  watch(
    () => route.query,
    (newQuery, oldQuery) => {
      handleImgParam(); // 路由变化时也调用处理函数
    }
  );

  // 处理表单提交
  const handleSubmit = async () => {
    if (!isFormValid.value || isSubmitting.value) return;

    try {
      isSubmitting.value = true;

      const params = {
        aid: router.currentRoute.value.query.aid,
        gen_type: formData.value.type,
        template_id: formData.value.template_id,
        prompt_text: formData.value.prompt,
        img: formData.value.url,
      };

      await AiAPI.generate(params);
      aiStore.getGenerateResults();
    } catch (error: any) {
      const { code } = error.response.data || {};
      if (code === 100201) {
        ElMessage.warning('Too many tasks submitted. Please try again later.');
      }
    } finally {
      isSubmitting.value = false;
    }
  };
</script>

<style lang="scss" scoped>
  @use '@/styles/variables' as *;

  .form-container {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 64px);
    padding: 0 16px;
    box-sizing: border-box;
  }

  .scrollable-content {
    flex: 1;
    overflow-y: auto; /* 允许中间内容滚动 */
    /* 隐藏滚动条 - Firefox */
    scrollbar-width: none;
    /* 隐藏滚动条 - Chrome, Safari 和 Edge */
    &::-webkit-scrollbar {
      display: none;
    }
  }

  .ai-form {
  }

  .form-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
    border-bottom: 1px solid $primary-border-color;
    padding: 16px 0px 24px 0px;
    &:last-child {
      border-bottom: none;
    }
  }

  .form-label {
    font-weight: 600;
    font-style: SemiBold;
    font-size: 16px;
    line-height: 100%;
    letter-spacing: 0%;
    color: #222222;
    margin-bottom: 8px;
  }

  .image-uploader {
    // height: 100%;
    // :deep(.el-upload-dragger) {
    //   height: 446px;
    // }
  }

  .textarea-container {
    position: relative;
  }

  .form-textarea {
    width: 100%;
    padding: 8px 16px;
    padding-bottom: 40px;
    border-radius: 8px;
    resize: none;
    outline: none;
    background-color: #f8f8f8;

    font-weight: 400;
    font-size: 14px;
    height: 170px;
    color: #222222;

    /* 添加占位符文本样式 */
    .form-textarea::placeholder {
      color: #7a7a7a; /* 与输入文本相同的颜色 */
    }
  }
  .prompt-bar {
    position: absolute;
    bottom: 12px;
    right: 16px;
    width: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .char-counter {
      font-size: 14px;
      color: #7a7a7a;
    }
    .ai-reselect-icon {
      cursor: pointer;
    }
  }

  .button-container {
    padding: 16px 0 40px;
    background-color: white; /* 确保按钮区域背景色与页面一致 */
  }

  .submit-button {
    width: 100%;
    height: 48px;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 18px;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.3s ease;
    background: linear-gradient(90deg, #f76b1b 0%, #dc3a0e 100%);

    &:disabled {
      background: #ccc;
      pointer-events: none;
    }
    &:hover:not(:disabled) {
      background: linear-gradient(90deg, #f78647 0%, #e1603d 100%);
    }
  }
</style>
